package dao

import (
	"order-srv/internal/model"
	"order-srv/libs"
	"strconv"
)

type IOrder interface {
	CreateOrder(order model.Order, orderGoodsSkuList []model.OrderGoodsSku) (id uint64, err error)
	UpDateOrder(id uint64, order model.Order) (err error)
	SelectOrderById(id uint64) (order model.Order, err error)
}

type Order struct {
}

func (_ Order) CreateOrder(order model.Order, orderGoodsSkuList []model.OrderGoodsSku) (id uint64, err error) {
	db := libs.GetDB()
	tx := db.Begin() // 同实例执行，单机事务
	// 订单表
	order.Id = libs.GetId()
	order.OrderNo = strconv.FormatUint(libs.GetId(), 10)
	order.GoodsCount = int64(len(orderGoodsSkuList))
	result := tx.Create(&order)
	if result.Error != nil {
		tx.Rollback()
		return order.Id, result.Error
	}

	// 订单商品表
	for i := 0; i < len(orderGoodsSkuList); i++ {
		orderGoodsSkuList[i].Id = libs.GetId()
		orderGoodsSkuList[i].OrderId = order.Id
	}

	result = tx.Create(&orderGoodsSkuList)
	if result.Error != nil {
		tx.Rollback()
		return order.Id, result.Error
	}
	tx.Commit()
	return order.Id, nil
}

func (_ Order) UpDateOrder(id uint64, order model.Order) (err error) {
	db := libs.GetDB()
	result := db.Model(&model.Order{Id: id}).Updates(order)
	if result.Error != nil {
		return result.Error
	}
	return err
}

func (_ Order) SelectOrderById(id uint64) (order model.Order, err error) {
	db := libs.GetDB()
	result := db.Preload("OrderGoodsSkus").First(&order, id)
	if result.Error != nil {
		return order, result.Error
	}
	return order, nil
}

func NewOrder() IOrder {
	return Order{}
}
